from django.db import models
from django.contrib import admin
from django.contrib.auth.models import User

from constants import ACCESS_LEVELS

# import the logging library
import logging

logging.basicConfig(filename='log.txt',level=logging.DEBUG)


def_max_length = 255

class Profile(models.Model):
    FARMER = 'FA'
    MEMBER_ORG = 'MO'
    VOLUNTEER = 'VO'
    GLEANING_COORDINATOR = 'GC'


    user = models.ForeignKey(User, unique=True)	
    address = models.CharField(max_length=def_max_length)
    city = models.CharField(max_length=def_max_length)
    county1 = models.CharField(max_length=def_max_length)
    county2 = models.CharField(max_length=def_max_length)
    county3 = models.CharField(max_length=def_max_length)
    email = models.CharField(max_length=def_max_length)
    age = models.CharField(max_length=def_max_length)
    phone = models.CharField(max_length=def_max_length)
    ecfirst_name = models.CharField(max_length=def_max_length)
    eclast_name = models.CharField(max_length=def_max_length)
    ecphone = models.CharField(max_length=def_max_length)
    ecrelationship = models.CharField(max_length=def_max_length)        
    access_level = models.CharField(max_length=25, choices=ACCESS_LEVELS, default=VOLUNTEER)

    class Meta:
        app_label = "user_profile"
        verbose_name = "User profile"
        verbose_name_plural = "User profiles"
        
        
    def __unicode__(self):
        return u'%s %s' % (self.user, self.address)
        
        
class ProfileAdmin(admin.ModelAdmin):

    def make_mailing_list(self, request, queryset):
        from emencia.django.newsletter.models import Contact
        from emencia.django.newsletter.models import MailingList

        subscribers = []
        for profile in queryset:
            contact, created = Contact.objects.get_or_create(email=profile.email,
                                                             defaults={#'first_name': profile.first_name,
                                                                       #'last_name': profile.last_name,
                                                                       'content_object': profile})
            subscribers.append(contact)
        new_mailing = MailingList(name='New mailing list',
                                  description='New mailing list created from admin/profile')
        new_mailing.save()
        new_mailing.subscribers.add(*subscribers)
        new_mailing.save()
        self.message_user(request, '%s succesfully created.' % new_mailing)
    make_mailing_list.short_description = 'Create a mailing list'

    actions = [make_mailing_list]
try:
    admin.site.register(Profile, ProfileAdmin)
except:
    pass
    
    
